<template>
	<view>

		<view class="cu-chat">
			<view class="dh-hint" v-if="fistone">
			  <view class="hint-hh" v-for="(item,index) in hintList ":key="index" @click="hintcli(item)">
          <view class="">
            {{item}}<image class="towardsr" src="https://www.iwangbang.com/skin/wx_mp_aixz/towardsr.png" mode=""></image>
          </view>
        </view>

			</view>
      <view class="" v-for="(item,index) in msgList" :key="index">
        <!-- AI消息 -->
        <view v-if="item.my == false"  class="cu-item" >
        	<view class="flex flex-direction align-center">
        		<image class="cu-avatar round chat-avatar" src="https://www.iwangbang.com/skin/wx_mp_aixz/logo.png">
        		<text  class="cuIcon-title" :class="[statusColor]"></text>
        	</view>
        	<view class="main">
        		<view class="content shadow" @click="">
              <text class="">{{item.type == 'word'? item.msg : ''}}</text>
        			<image v-if="item.type == 'word' ? false : true" class="uimage" :src="item.type == 'word' ? '' : item.msg" @click="showImage(item.msg)"></image>
        		</view>
        	</view>
        </view>
          
        <!-- 用户消息 -->
        <view  v-if="item.my == true"  class="cu-item self" >
        	<view class="main">  
        		<view class="content bg-cyan shadow yhmsg" @click="">
        			<text>{{item.msg}}</text>
        		</view>
        	</view>
        	<image class="cu-avatar round" :src="headimg == '' ? 'https://www.iwangbang.com/skin/wx_mp_aixz/navigation/my.png' : headimg">
        </view>  
      </view>


		</view>
<!-- cu-bar foot input -->
		<view class=" cu-bar foot input" :style="[{bottom:inputBottom}]">
			<!-- <input   v-model="describe" class="solid padding-lr" :adjust-position="false" :focus="false" maxlength="1000"
				cursor-spacing="0" :placeholder="loading ? 'AI正在思考中，请稍后~' : '用一句简短的话描述您的问题'"
			 @confirm="sendMsg"></input> -->
       <textarea class="asfasd padding-lr" v-model="describe" :style="{height: textheight,maxHeight:textmaxHeight}" :disable-default-padding='true'  name="" id="" cols="30" rows="10" :auto-height="fsddfsd" :fixed="true" @linechange="linechange" maxlength="-1" 
         @confirm="sendMsg" :placeholder="loading ? 'AI正在思考中，请稍后~' : '用一句简短的话描述您的问题'" cursor-spacing="20" :adjust-position="false" :focus="false" :show-confirm-bar='false'></textarea>
       
       
<view class="action">
				<text class="cuIcon-emojifill text-grey"></text>
			</view>
			<button class="cu-btn  shadow sendtext" :disabled="loading" @click="sendMsg">
				<text class="cuIcon-loading2 cuIconfont-spin" ></text>发送
			</button>
		</view> 
		
    <aidialogue ref="aidialo" @backHome='backHome'></aidialogue>
	</view>
</template>   

<script>
  import  aidialogue  from '../../components/aichat/aichat.vue'
	export default {
    components:{
      aidialogue
    },
    onShareTimeline:function(res){
          return {
            title: '小帮观影，我的AI影评顾问',
            imageUrl:'https://www.iwangbang.com/skin/wx_mp_xbgy/share.jpg',
            query: "inviteCode="+uni.getStorageSync('wbyun_icode')
          }
        },
    onShareAppMessage(res) {
      console.log(res);
      console.log(uni.getStorageSync('wbyun_icode'));
      return {
            title: '小帮观影，我的AI影评顾问',
            imageUrl:'https://www.iwangbang.com/skin/wx_mp_xbgy/share.jpg',
            path: '/pages/index/index?inviteCode=' + uni.getStorageSync('wbyun_icode')
          }
    },
		data() {
			return { 
        textheight:'90rpx',
        textmaxHeight:'90rpx',
				loading: false,
        aisse:"",
        hhtext:[
          {'txt':'飞翔的孔雀'},
          {'txt':'国风山水画'},
          {'txt':'汉服手绘女孩'},
          {'txt':'拿着武器的武侠少年'},
          {'txt':'水中美女写真'},
          {'txt':'夏日海滩场景'},
          {'txt':'漂浮的城堡'},
          {'txt':'星空下的雪山'},
          {'txt':'国风汉服少女'},
        ],
        msgList:[
 
        ],
				msgContent: "",
				describe: "", 
				inputBottom: 0,
				bottomFuncShow: false,
				chatAsset: {},
				assetType: 'n',
				statusColor: 'text-red',
				statusTimer: null,
				msgLoading: false,
        usertxt:'',
        typedText:'',
        currentIndex:0,
        safe:0,
        fistone:true,
        headimg:'',
        hintList:[]
        
			}
		},
		computed: {
      
		},
		watch: {
            
		},
		 onShow() {
       this.gethint()
       this.headimg = uni.getStorageSync('wbyun_headimg')
       console.log(this.headimg,'222');
        uni.getSystemInfo({
          success:(res)=> {
            console.log(res.safeArea,res.screenHeight);
          let tabBarHeight =  res.screenHeight - res.safeArea.bottom
          console.log(tabBarHeight);
       
          this.safe = tabBarHeight + 50
          }
        })
         uni.onKeyboardHeightChange(res => {
           if(res.height !== 0) {
             this.inputBottom = res.height - this.safe  +'px' 
             console.log(this.inputBottom,'1111');
           }else {
             this.inputBottom = res.height +'px'
           }
           
           console.log(res.height)
         })
		},
    onLoad(){
 
      　
    },
		onHide() { 

		}, 
    mounted() {
  
    },
		methods: {   
      gethint() {
        uni.request({
        	url:getApp().globalData.apiDomain +'/mp/aixz_aihh_tsc' ,
        	method: 'GET',
        	header: {
        		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
        		'token': uni.getStorageSync('wbyun_token'),
            'wbapp':'weixin_mp_xbgy'
        	},
        	data: {},
        	dataType: 'json',
        	success:  res => {
            console.log(res,'1112');
        		if (res['data']['code'] == 200) {
              this.hintList = res.data.datas
                }

        		
        	},
        	fail: () => {},
        	complete: () => {
        	}
        });
      },
      // 打字输出流
      startTyping(e,id,k) {
        let text = e
        this.msgList.map(item => {
          const timer = setInterval(() => {
            if(item.id == id) {
              if(e[this.currentIndex] == undefined) {
                clearInterval(timer);
                return 
              }else {
                item.msg += text[this.currentIndex]
                this.currentIndex++; 
              }
              }
            
          }, 100);
        })
      
      },
			 sendMsg() {
         if(uni.getStorageSync('wbyun_token')==null || uni.getStorageSync('wbyun_token')==''){
           	uni.navigateTo({
           		url:'/pagesA/tellogin/tellogin'
           	})
            return
           }
       const regex = /^\s*$/;
       if(this.describe == '' || regex.test(this.describe)) {
         uni.showToast({
         	title: '请先输入您的问题!',
         	icon: 'none'
         });
         return
       }
       
        uni.request({
        	url: getApp().globalData.apiDomain+'mp/aixz_aihh_model',
        	method: 'POST',
        	header: {
        		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
        		'token': uni.getStorageSync('wbyun_token'),
            'wbapp':'weixin_mp_xbgy'
        	},
        	data: {},
        	dataType: 'json',
        	success:  res => {
            console.log(res);
        		if (res['data']['code'] == 200) {
               
              if(res.data.datas.model == 'dall') {
                console.log(this.describe);
                uni.navigateTo({
                  url:"/pagesC/drawingse/drawingse?text="+ this.describe
                })
                
              }else {
                uni.navigateTo({
                  url:"/pagesC/universe/universe?text="+ this.describe
                })
              }
              this.describe = '' 
              
       
        			return;
        		}else if(res['data']['code'] == '100500') {
              uni.showToast({
              	title:res['data']['msg'],
              	icon: 'none'
              });
              uni.setStorageSync('wbyun_token', '');
            }
        	},
        	fail: () => {},
        	complete: () => {
        	}
        });
       
         
       
       
       
       
       // let txt = ''
       // txt = this.describe
       //  this.describe = ''
       //  this.fistone = false
       //  this.msgList.push({
       //    msg:txt,
       //    my:true
       //  })
       //  this.msgList.push({
       //    msg:'',
       //    my:false,
       //    type:'word'
       //  })
        
       //  this.msgList.map((item,index)=> {
       //    if(index == this.msgList.length -1) { 
       //      const timer = setInterval(() => {
       //            let text = '小帮正在思考中请稍等...'
       //            item.msg += text[this.currentIndex]
       //            this.currentIndex++; 
       //            if(this.currentIndex == text.length) {
       //              clearInterval((timer))
       //              return
       //            }
       //      }, 50);
       //    }
       //  })
       //  this.currentIndex = 0
       //  uni.request({
       //  	url: getApp().globalData.apiDomain+'ai/draw',
       //  	method: 'POST',
       //  	header: {
       //  		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
       //  		'token': uni.getStorageSync('wbyun_token'),
       //      'wbapp':'weixin_mp_xbgy'
       //  	},
       //  	data: {
       //  		'task': 'txt2img.sd',
       //      'text':txt,
       //      'vpsoft':'ai_hyz'
       //  	},
       //  	dataType: 'json',
       //  	success:  res => {
       //      console.log(res);
       //  		if (res['data']['code'] == 200) {
       //        this.getdrawing(res.data.datas.uid)
              

       //  			return;
       //  		}else if(res['data']['code'] == '100500') {       //        uni.showToast({       //        	title:res['data']['msg'],       //        	icon: 'none'       //        });       //        uni.setStorageSync('wbyun_token', '');       //      } else { 
       //        setTimeout(()=> {
       //          this.msgList.map((item,index) => {
       //            if(index == this.msgList.length -1) {
       //              item.msg = res['data']['msg']
       //            }
       //          })
       //        },1500)
       //  			uni.showToast({
       //  				title: res['data']['msg'],
       //  				icon: 'none'
       //  			});
       //  		}
       //  	},
       //  	fail: () => {},
       //  	complete: () => {
       //  	}
       //  });
         
			},
      showImage(e) {
        let imgPaths = [] 
        imgPaths.push(e)
        uni.previewImage({
        			current: 0,
        			urls: imgPaths,//图片路径是个数组，数组里面放图片的全路径
        			longPressActions: {  //长按保存图片到相册
        				itemList: ['保存图片'],
        				success: (data)=> {
        					uni.saveImageToPhotosAlbum({ //保存图片到相册
        						filePath: payUrl,
        						success: function () {
        							uni.showToast({icon:'success',title:'保存成功'})
        						},
        						fail: (err) => {
        							uni.showToast({icon:'none',title:'保存失败，请重新尝试'})
        						}
        					});
        				},
        				fail: (err)=> {
        					console.log(err.errMsg);
        				}
        		}
        	})
      },
     linechange(e) {
       console.log(e.detail);
        if(e.detail.lineCount == 1) {
          this.textheight = '90rpx'
          this.textmaxHeight = '90rpx'
       }else if(e.detail.lineCount == 2) {
         this.textheight = '120rpx'
         this.textmaxHeight= '120rpx'
       }else if(e.detail.lineCount == 3) {
         this.textheight = '157rpx'
         this.textmaxHeight= '157rpx'
       }else
       console.log(this.textheight);
     },
      getdrawing(uid) {
        
        let timer = setTimeout(()=>{
            uni.request({
            	url: 'https://ai.iwangbang.com/draw/status?uid=' + uid,
            	method: 'GET',
            	header: {
            		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
            		'token': uni.getStorageSync('wbyun_token'),
                'wbapp':'weixin_mp_xbgy'
            	},
            	data: {},
            	dataType: 'json',
            	success:  res => {
                console.log(res);
            		if (res['data']['code'] == 200) {
                    clearInterval(timer)
                    if(res.data.datas.data.cdn == undefined) {
                      this.getdrawing(uid)
                    }else if(  res.data.datas.data.cdn == '' ) {
                      this.msgList.splice(this.msgList.length - 1,1)
                        this.msgList.push({
                          msg: '当前咨询人数较多，请稍后再试...',
                          my:false
                        })
                    }else {
                      this.msgList.splice(this.msgList.length - 1,1)
                        this.msgList.push({
                          msg: res.data.datas.data.cdn,
                          my:false
                        })
                    }
                  
                  
            			return;
            		} else { 
            			uni.showToast({
            				title: res['data']['msg'],
            				icon: 'none'
            			});
            		}
            	},
            	fail: () => {},
            	complete: () => {
            	}
            });
        },1000)
        
        
        
        
      },
      hintcli(e) {
        this.describe = e
      },
    
    

			
			
			mockReply() {
			
			}
		}
	}
</script>

<style>
	page {
		padding-bottom: 200upx;
	}
	.cu-chat .chat-avatar.cu-avatar {
	    width: 82upx;
	    height: 82upx;
	}
	.cu-item:not(.first) {
		padding-bottom: 0upx;
	}
	.cu-item.sec {
		padding-top: 0upx;
	}
	.main .content {
		word-wrap: break-word;
	}
	.foot {
/* 		padding-top: 20upx;
		padding-bottom: 0upx !important;
    margin-bottom: 0 !important; */
    display: flex !important;
	}
	.foot .cu-btn {
		margin-right: 20upx;
	}
	.foot .action.func {
		margin-left: 30upx;
	}
  
  .yhmsg>text {
    width: 100%;
  }
  .awaitts {
    width: 100%;
    height: 40rpx;
  }
  .cu-bar {
    height: 180rpx;
    background-color: rgb(246,250,252) !important;
   
  }
  .padding-lr {
    /* height: 90rpx !important; */
     box-shadow: -10px -10px 50px 0px rgb(225 227 228);
  }
  .asfasd {
    flex: 1;
    margin: 0 20rpx;
    background-color: rgb(246,250,252);
    padding: 20rpx;
    font-size: 36rpx;
  }
  .dh-hint {
    width: 90%;
    height: 400rpx;
    margin: 150rpx auto 0 auto;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  .hint-hh {
    width: 30%;
    padding: 25rpx;
    border-radius: 20rpx;
    text-align: center;
    display: flex;
    align-items: center;
    margin: 10rpx 0;
    background-color: rgb(247,247,247);
  }
 .towardsr {
   width: 50rpx;
   height: 30rpx;
   margin-bottom: -7rpx;
 }
 .sendtext {
   background-color: #4193FE !important;
   color: #fff;
 }
</style>
